UIOPTIONS.HeaderWithCart=true

var ShopRow = React.createClass({

    render:function(){
        var picture=this.props.picture||"http://cdn.fruitday.com/images/2015-05-21/1432190870_pic.jpg";

        return (<div className="col-xs-6 col-md-3 col-lg-2 grid-item">
            <img className="img-responsive img-rounded" src={picture}/>
        </div>)
    }
});

var ProductList = React.createClass({
    loadedUrl:'',
    getInitialState: function() {
        return {products: []};
    },
    componentDidMount: function() {

    },
    render: function() {
        //console.log(this.props.url);
        var self=this;
        var url=self.props.url||'/api/products';
        if(self.loadedUrl!=url){
            $.get(url,function(data){
                //console.log(data.content);
                self.loadedUrl=url;
                self.setState({products: data.content});
            })
        }
        var rows = [];
        var lastCategory = null;
        this.state.products.map(function(product) {
            rows.push(<ProductRow product={product} key={product.name} />);
            lastCategory = product.category;
        });
        return (

                <div className="ProductList row grid clear-both">{rows}</div>
        );
    }
});

var ProductRow = React.createClass({
    handleOpenDetail:function(productId){
      toPage('ProductDetailPage',{customerId:customerId,id:productId});
      return false;
    },
    getInitialState: function() {
        return {status: ''};
    },
    componentDidMount: function() {

    },
    render: function() {
        var product = this.props.product;
        var picture=product.picture?'/api/thumb/'+product.picture+'/256/256':"http://cdn.fruitday.com/product_pic/4192/1/1-370x370-4192-H1C9S22B.jpg";
        return (
        <div className="panel panel-success col-xs-4 col-md-3 grid-item">
        <a className="block" onClick={this.handleOpenDetail.bind(this,product.id)} href="javascript:;">
            <img className="img-responsive img-rounded" src={picture}/>
            <div className="caption-xs border-radius-base">{product.price} ¥ </div>
            <div className="caption-md hidden-xs border-radius-base">{product.name}</div>
        </a>
        </div>

        );
    }
});

var NavBar = React.createClass({
    handleShowLoginModal:function(){
        $('#loginModal',"#wrapper").modal('show');
    },
    render: function() {
        var rightButtons=[];
            var flag=$.cookie("flag")||"";
            if(flag.indexOf("p")>=0){
                    rightButtons.push(<li><a href={"/manage/main.html"} >管理</a></li>);
            }
        if(this.props.customerId){
            return(<div id="sidebar-wrapper">
                   <ul className="sidebar-nav">
                        <li className="sidebar-brand">
                           <UserBadge customer={this.props.customer}/>
                        </li>
                        <li className="clearfix"><a onClick={function(){toPage('HomePage',{customerId:this.props.customerId},'/index.html')}.bind(this)}>首页</a></li>
                        <li><a href="javascript:;">我的订单</a></li>
                        <li><a href="javascript:;">我的购物车</a></li>
                        <li><a href="javascript:;">设置</a></li>
                        {rightButtons}
                   </ul>
               </div>
               );
        }else{
            return(<div id="sidebar-wrapper">
                   <ul className="sidebar-nav">
                        <li className="sidebar-brand">
                           <UserBadge customer={this.props.customer}/>
                           <p className="btn-group" role="group">
                                <button onClick={this.handleShowLoginModal.bind(this)} className="btn btn-warning">登录</button>
                                <button onClick={function(){toPage('RegPage')}.bind(this)} className="btn btn-primary">注册</button>
                           
                           </p>

                        </li>
                        <li className="clearfix"><a onClick={function(){toPage('HomePage',{customerId:this.props.customerId},'/index.html')}.bind(this)}>首页</a></li>

                   </ul>
               </div>
               );
        }

    }
});

/****** pages *********/

var HomePage = React.createClass({
  render:function(){
    return (
        <div>
        <AdList level={1}/>
        <AdList level={2}/>
        <ProductList />
        </div>
        )
  }
})

var RegPage = React.createClass({
    handleReg:function(){
        console.log($('form',this.getDOMNode()).serializeArray());
        var data={};
        $('form',this.getDOMNode()).serializeArray().map(function(kv){
            data[kv.name]=kv.value;
        });
        data.code='xxx';
        data.mobile=data.username;
        $.post('/api/customers',data,function(data){
            console.log(data)
        })
        return false;
    },
    render:function(){
        return (
<div className="panel">
 <div className="panel-body">
    <form>
      <div className="form-group">
        
        <input type="text" className="form-control" name="username" id="username" placeholder="手机号" data-rule-required="true"  data-msg-required="此项不能为空！" data-rule-minlength="6"/>
        <label for="username" className="alert alert-default">仅支持中国大陆地区手机号码</label>
      </div>
      <div className="form-group">
        
        <input type="password" className="form-control" name="password" id="password" placeholder="密码" data-rule-required="true"  data-msg-required="此项不能为空！" data-rule-minlength="6"/>
        <label for="password" className="alert alert-default">请输入4-40位字符作为密码</label>
      </div>
      
      <button type="button" onClick={this.handleReg.bind(this)} className="btn btn-primary col-xs-12 col-md-2">注册</button>
      <hr/>
      <p>已有账号？请<a href="javascript:;" onClick={function(){toPage('LoginPage')}.bind(this)}>直接登录</a></p>
    </form>
 </div>
</div>
            )
    }
})

var ShopPage = React.createClass({
    getInitialState: function() {
        return {
            shop:{} 
        };
    },
    componentDidMount: function() {
        $.get('/api/shops/'+this.props.shopId,function(data){
            this.setState({shop:data})
        }.bind(this))
    },
    render:function () {
        var shop=this.state.shop||{};
        return (
            <div>
            <h3>{shop.name}</h3>
            <ProductList url={"/api/shops/"+this.props.shopId+"/products"}/>
            </div>)
    }
})

var ProductDetailPage = React.createClass({
    handleAdd2Cart:function(){
        API.customerPostCart({customerId:this.props.customerId,product_id:this.state.product.id,_amount:1},function(data){
            CART_BTN.setState({cart:data})
        })
    },
    getInitialState: function() {
        return {product:{name:''}}
    },
    componentDidMount: function() {
        API.getProduct({productId:this.props.id},function(data){
            this.setState({product:data});
        }.bind(this))
    },
    render:function(){
        var product=this.state.product;
        var partner=product.partner||{};
        var location=product.location||{};

        var i=0;
        var sliderItems=(product.pictureSet||[]).map(function(pic){
            i++;
            return {index:i,src:'/api/thumb/'+pic+'/512/512',active:i==1}
        })
        var pictures=(product.pictureSet||[]).map(function(pic){
            return <img className="col-xs-12 col-md-6" src={'/api/thumb/'+pic+'/512/512'}/>
        })
        var slider=""
        if(sliderItems.length>0){
            slider=<Slider items={sliderItems} />
        }
        return (
            <div className="row">
                {slider}
                <hr/>
                <div className="col-xs-12 col-md-4">
                    <table width="100%" className="table table-striped table-condensed">
                        <tr><td width="60"><label>价格</label></td><td>{product.price}</td><td width="20"></td></tr>
                        <tr><td width="60"><label>销量</label></td><td>{product.sold}</td><td width="20"></td></tr>
                        <tr><td width="60"><label>库存</label></td><td>{product.stock}</td><td width="20"></td></tr>
                        <tr><td width="60"><label>说明</label></td><td>{product.remark}</td><td width="20"></td></tr>
                    </table>
                    <div className="btn-group" role="group">
                        <button onClick={this.handleAdd2Cart.bind(this)} className="btn btn-lg btn-primary">加入购物车</button>
                        <button className="btn btn-lg btn-success">立刻购买</button>
                    </div>
                    
                </div>
                <hr/>
                <div >
                {pictures}
                </div>
            </div>
            )
      }
})

var CartPage = React.createClass({
    getInitialState: function() {
        return {cart:{}}
    },
    componentDidMount: function() {
        API.customerCart({customerId:this.props.customerId},function(data){
            this.setState({cart:data});
        }.bind(this))
    },
    render:function(){
        var cart=this.state.cart||{};
        var alert=""
        var items=[]
        if(!cart.itemCount){
            alert=<div className="alert alert-info">您的购物车还没有商品，快去挑选心爱的商品吧！</div>
        }else{
            var itemGrouped=cart.groups.map(function(group){
                return(<div className="col-xs-12">
                    <div>{group.shopName} - {group.total} </div>
                    <table width="100%" className="table table-striped table-condensed">
                    {group.cartItems.map(function(item){
                        return (<tr><td>{item.product.name}</td><td>{item.amount}</td><td>{item.total}</td></tr>);
                    })}
                    </table>
                    </div>)
                
            });
        }
        return (
        <div className="panel">
            <div className="row panel-body">
            <h3 className="col-md-4">购物车<small>{cart.itemCount}件商品</small></h3>
            {alert}
            {itemGrouped}
            <div className="pull-right col-md-4">
                <h3 className="btn-group">金额：<small>{cart.total} <button className="btn btn-lg btn-primary">去结账</button></small></h3>
            </div>
            
            </div>
        </div>);
    }
})


